// pages/order-detail/order-detail.js
const apiService = require('../../utils/apiService.js');

Page({
  data: {
    order: null,
    loading: true,
    orderNumber: '',
    restaurant: '',
    status: '',
    statusText: '',
    statusColor: '',
    createTime: '',
    itemCount: 0,
    dishes: [],
    deliveryTime: null,
    rating: null,
    participants: []
  },

  onLoad(options) {
    const { orderId } = options;
    if (orderId) {
      this.loadOrderDetail(orderId);
    } else {
      wx.showToast({
        title: '订单不存在',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载订单详情
  async loadOrderDetail(orderId) {
    this.setData({ loading: true });
    
    try {
      const orderData = await apiService.getOrderDetail(orderId);
      this.formatOrderData(orderData);
    } catch (error) {
      console.error('获取订单详情失败:', error);
      wx.showToast({
        title: '获取订单详情失败',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 格式化订单数据
  formatOrderData(orderData) {
    // 从API返回的数据中提取order对象
    const order = orderData.order || orderData;
    
    // 格式化菜品数据 - 使用API真实字段
    const dishes = (order.dishes || []).map(dish => ({
      name: dish.name || '未知菜品',
      quantity: dish.quantity || 1,
      description: dish.description || dish.desc || '',
      image: dish.image || dish.imageUrl || '',
      flavor: dish.flavor || '',
      note: dish.note || '',
      options: dish.options || []
    }));

    // 格式化参与者数据
    const participants = (order.participants || []).map(participant => ({
      nickname: participant.nickname || '未知用户',
      itemCount: participant.item_count || 0,
      dishes: (participant.dishes || []).map(dish => ({
        name: dish.name || '未知菜品',
        quantity: dish.quantity || 1,
        flavor: dish.flavor || '',
        note: dish.note || ''
      }))
    }));

    // 状态映射
    const statusMap = {
      'pending': { text: '待确认', color: 'warning' },
      'confirmed': { text: '已确认', color: 'info' },
      'cancelled': { text: '已取消', color: 'tertiary' },
      'completed': { text: '已完成', color: 'success' },
      'unknown': { text: '未知状态', color: 'default' }
    };

    const statusInfo = statusMap[order.status] || statusMap['unknown'];

    this.setData({
      order: orderData,
      orderNumber: order.order_id || order.id || '未知订单',
      restaurant: order.room?.title || '未知餐厅',
      status: order.status || 'unknown',
      statusText: statusInfo?.text || '未知状态',
      statusColor: statusInfo?.color || 'default',
      createTime: order.created_at || order.createdAt || '未知时间',
      totalAmount: order.total_price || order.totalAmount || 0,
      itemCount: order.item_count || order.itemCount || dishes.length,
      dishes: dishes,
      deliveryTime: order.delivery_time || null,
      rating: order.rating || 0,
      participants: participants,
      loading: false
    });
  },


  // 取消订单
  async cancelOrder() {
    const { order } = this.data;
    wx.showModal({
      title: '确认取消',
      content: `确定要取消订单${order.order_id || order.id}吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await apiService.cancelOrder(order.order_id || order.id);
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            // 更新状态
            this.setData({
              'order.status': 'cancelled',
              'order.statusText': '已取消',
              'order.statusColor': 'tertiary',
              status: 'cancelled',
              statusText: '已取消',
              statusColor: 'tertiary'
            });
          } catch (error) {
            wx.showToast({
              title: '取消订单失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  // 确认订单
  async confirmOrder() {
    const { order } = this.data;
    wx.showModal({
      title: '确认订单',
      content: `确定要确认订单${order.order_id || order.id}吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await apiService.confirmOrder(order.order_id || order.id);
            wx.showToast({
              title: '订单已确认',
              icon: 'success'
            });
            // 更新状态
            this.setData({
              'order.status': 'confirmed',
              'order.statusText': '已确认',
              'order.statusColor': 'info',
              status: 'confirmed',
              statusText: '已确认',
              statusColor: 'info'
            });
          } catch (error) {
            wx.showToast({
              title: '确认订单失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  // 评价订单
  rateOrder() {
    wx.showToast({
      title: '评价功能开发中',
      icon: 'none'
    });
  },

  // 再次下单
  reorder() {
    wx.showToast({
      title: '再次下单功能开发中',
      icon: 'none'
    });
  },

  // 联系商家
  contactMerchant() {
    wx.showToast({
      title: '联系商家功能开发中',
      icon: 'none'
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 分享订单
  shareOrder() {
    wx.showActionSheet({
      itemList: ['分享给朋友', '生成海报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.showToast({
            title: '分享功能开发中',
            icon: 'none'
          });
        } else if (res.tapIndex === 1) {
          wx.showToast({
            title: '海报生成功能开发中',
            icon: 'none'
          });
        }
      }
    });
  },

  // 联系商家
  contactMerchant() {
    wx.showToast({
      title: '联系功能开发中',
      icon: 'none'
    });
  },

  // 修改订单
  editOrder() {
    wx.showModal({
      title: '修改订单',
      content: '确定要修改这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 跳转到点单页面，并传递订单信息
          wx.navigateTo({
            url: `/pages/order/order?orderId=${this.data.order.id}&edit=true`
          });
        }
      }
    });
  },

  // 清空订单
  clearOrder() {
    wx.showModal({
      title: '清空订单',
      content: '确定要清空这个订单吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          // 调用API清空订单
          this.clearOrderItems();
        }
      }
    });
  },

  // 清空订单项目
  async clearOrderItems() {
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 这里应该调用API清空订单
      // await apiService.clearOrder(this.data.order.id);
      
      // 暂时显示成功提示
      wx.hideLoading();
      wx.showToast({
        title: '订单已清空',
        icon: 'success'
      });
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
